package com.ctgu.admin.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctgu.admin.system.domain.Article;
import com.ctgu.admin.system.domain.Like;
import com.ctgu.admin.system.service.ArticleService;
import com.ctgu.admin.system.service.LikeService;
import com.ctgu.component.shiro.ShiroUtil;
import com.ctgu.modules.system.domain.User;
import org.dom4j.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/system/like")
public class LikeController {
    @Autowired
    private LikeService likeService;

    @Autowired
    private ArticleService articleService;

    @GetMapping("/add/{articleId}")
    @ResponseBody
    public Map<String,Object> getLike(@PathVariable("articleId") Long articleId){
        System.out.println("点赞的文章：ArticleID============="+articleId);
        User user = ShiroUtil.getSubject();
        Map<String,Object> result = new HashMap<String,Object>();
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id",articleId);
        wrapper.eq("user_id",user.getId());
        Like one = likeService.getOne(wrapper);
        String msg;
        boolean flag = false;
        if(one != null){
            if(one.getStatus() == 1){
                result.put("msg","点赞失败,已经点赞过该文章") ;
            }else{
                one.setStatus(1);
                likeService.updateById(one);
                flag = true;
            }
        }else{
            Like like = new Like();
            like.setArticleId(articleId);
            like.setUserId(user.getId());
            like.setStatus(1);
            likeService.save(like);
            flag = true;
        }
        if(flag){
            // 点赞数+1
            Article article = articleService.getById(articleId);
            article.setLikeNumber(article.getLikeNumber() + 1);
            articleService.save(article);
            result.put("msg","点赞成功");
        }

        return result;
    }

    @GetMapping("/remove/{articleId}")
    @ResponseBody
    public String removeLike(@PathVariable("articleId") Long articleId){
        User user = ShiroUtil.getSubject();

        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id",articleId);
        wrapper.eq("user_id",user.getId());
        Like like = likeService.getOne(wrapper);

        like.setStatus(0);
        likeService.updateById(like);

        // 点赞数-1
        Article article = articleService.getById(articleId);
        article.setLikeNumber(article.getLikeNumber() - 1);
        articleService.save(article);

        return "取消点赞成功";

    }

}
